/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package br.edu.utfpr.db;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class DatabaseManager {
    public static String HOST;
    public static String PORT;
    public static String LOGIN;
    public static String PASSWORD;
    public static String DATABASE;
    
    public static Connection conn;
    public static boolean execute(String arquivoSQL) throws FileNotFoundException, IOException, SQLException {
        /* Prepara o arquivo que contém as instruções SQL do schema */
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(arquivoSQL)));
        StringBuffer sb = new StringBuffer();

        String line;

        while ((line = br.readLine()) != null) {
            if (line.contains(";")) {
                sb.append(line);
                
                PreparedStatement ps = DatabaseManager.prepareStatement(sb.toString());
                ps.execute();
                System.out.println("Executando: " + sb.toString());
                /* Limpa o buffer */
                sb = new StringBuffer();
            }else{
                sb.append(line);
            }
        }
        DatabaseManager.close();

        return true;
    }
  public static Connection getMyDConnection() throws SQLException, ClassNotFoundException, IOException {
        Class.forName("com.mysql.jdbc.Driver");
        return DriverManager.getConnection("jdbc:mysql://"+HOST+":"+PORT+"/"+DATABASE, LOGIN, PASSWORD);
    }

    public static Connection connect(){
        try {
            return DatabaseManager.getMyDConnection();
        } catch (Exception ex) {
             ex.printStackTrace();
             return null;
        }
    }
    public static void close(){
        try {
            conn.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    public static PreparedStatement prepareStatement(String sql){
        conn = DatabaseManager.connect();
        PreparedStatement ps = null;
        try {
            ps = conn.prepareStatement(sql);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return ps;
    }
}
